/*
 * Created on Jun 9, 2010
 */
package com.mgmaps.utils;

import javax.microedition.lcdui.*;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.control.GUIControl;
import javax.microedition.media.control.VideoControl;
import com.mgmaps.app.APPCommands;
import com.mgmaps.app.APPMidlet;
import com.mgmaps.tools.UITools;

/**
 * Take a photo.
 *
 * @author CristiS
 * @version 1.0
 */
public class CaptureImage implements ICaptureImage, CommandListener {
  
  private CaptureImage instance;
  private Player player;
  private VideoControl control;
  private Form form;
  private Displayable parent;
  
  public CaptureImage getInstance() {
    if (instance == null)
      instance = new CaptureImage();
    return instance;
  }
  
  private CaptureImage() {
  }
  
  public void showCamera(String title, Displayable p) {
    try {
      player = Manager.createPlayer("capture://video");
      player.realize();
    
      control = (VideoControl) player.getControl("VideoControl");
      Item item = (Item) control.initDisplayMode(GUIControl.USE_GUI_PRIMITIVE, null);
      
      form = UITools.buildForm(form, title, new Item[] { item }, 
          new Command[] { APPCommands.instance.takePhotoCommand, APPCommands.instance.backCommand },
          this);
      
      parent = p;
      Display.getDisplay(APPMidlet.instance).setCurrent(form);
      
      player.start();
    }
    catch (Exception ex) {
      ExtLogger.handle(ex, false, "Error showing camera");
    }
  }

  public byte[] takePhoto() {
    try {
      final byte[] data = control.getSnapshot(null);
      commandAction(APPCommands.instance.backCommand, form);
      return data;
    }
    catch (Exception ex) {
      return null;
    }
  }
  
  public void commandAction(Command cmd, Displayable disp) {
    if (cmd == APPCommands.instance.backCommand) {
      Display.getDisplay(APPMidlet.instance).setCurrent(parent);
      
      if (player != null) {
        try {
          player.close();
        }
        catch (Exception ex) {
        }
        player = null;
      }
      control = null;
    }
    
    else if (cmd == APPCommands.instance.takePhotoCommand)
      takePhoto();
  }
}
